<script setup>
import {ref , watch} from 'vue'
import kong from '../../components/index/kong.vue'
import btnModule from '../../components/index/btnModule.vue'
import { httpRequest } from '../../utils/http';
import { onUnload } from '@dcloudio/uni-app';
/**
* 页面tab显示
* 0为抖音 1为视频号
*/ 
const isShow = ref(0)
const phone = ref('') //当前输入的电话号
const phoneCode = ref('') //验证码
const phoneList = ref([]) //页面显示的phone信息数组
const url = ref() //二维码路径

//发送请求获取手机号List
const getPhoneList = async() => {
    const res = await httpRequest('/api/releTiktokList','POST',{
        businessId:uni.getStorageSync('business').businessId
    })
    console.log(res.data);
    phoneList.value = res.data
}
getPhoneList()

//添加账号弹窗ref
const input = ref()

//打开添加账号弹窗
const openInput = () => {
    input.value.open('center')    
}

//关闭添加账号弹窗
const closeInput = () => {
    input.value.close()
}

//删除抖音(视频号)号方法
const delPhone = async(e) => {
    const res = await httpRequest("/api/delReleTiktokbyId","POST",{
        id:e
    })
    getPhoneList()
    uni.showToast({title:'删除成功',icon:'none'})
}

const qrCode = ref() //二维码弹窗ref
const timeId = ref() //getLoginType定时器
const timer = ref() //getLoginType2定时器
const timeQR = ref() //getCode2定时器
const vcode = ref() //手机验证码弹窗ref
const code = ref('') //验证码参数
const timeQRTime = ref(0)
watch(timeQRTime, (newVal, oldVal) => {
    console.log(newVal, oldVal);
    if(newVal == 1){
        timeQR.value = setInterval(async() => {
            const res = await httpRequest('/api/getLoginType','POST',{
                phone:phone.value,
                name:'code2'
            })
            if(res.data == 'code2'){
                code.value = res.data
                qrCode.value.close()
                vcode.value.open()
                uni.hideLoading()
                clearInterval(timeQR.value)
                clearInterval(timeId.value)
                uni.showToast({title:'验证码发送成功',icon:'none'})
                timeQRTime.value = 0
            }
        }, 2000);
    }
});

//点击添加账号确认函数
const verify = async() => {
    //正则校验输入的手机号
    if(/^(?:(?:\+|00)86)?1[3-9]\d{9}$/.test(phone.value)){
        uni.showLoading({
            title: '授权中',
            mask: true
        })
        //发送添加请求
        uni.request({
            url: 'https://www.diandianyouke.cn:8081/api/addReleTiktok',
            data: {
                businessId:uni.getStorageSync('business').businessId,
                phone:phone.value
            },
            header: {
                Accept: 'application/json',
                'Content-Type': 'application/x-www-form-urlencoded'
            },
            method: 'POST',
            timeout:300000,
            success: ({ data, statusCode, header }) => {
                // data.success为true则请求成功
                //关闭弹窗 清除定时器 提示授权成功
                if(data.data == 'err3'){
                    clearInterval(timeId.value)
                    uni.showToast({title:'授权次数过多,请稍后再试',icon:'none'})
                } 
                if(data.success){
                    input.value.close()
                    uni.hideLoading()
                    clearInterval(timeId.value)
                    clearInterval(timer.value)
                    clearInterval(timeId2.value)
                    clearInterval(timer2.value)
                    uni.showToast({title:'授权成功',icon:'none'})
                    vcode.value.close()
                    qrCode.value.close()
                    getPhoneList()
                }else{
                    clearInterval(timeId.value)
                    clearInterval(timer.value)
                    clearInterval(timeId2.value)
                    clearInterval(timer2.value)
                    uni.showToast({title:'授权失败',icon:'none'})
                }
            },
            fail: (error) => {
                console.log(error);
                clearInterval(timeId.value)
                clearInterval(timer2.value)
                uni.showToast({title:'授权失败',icon:'none'})
            }
        })

        //开启定时器循环请求登陆方式(二维码||验证码)
        
         timeId.value = setInterval(async() => {
            const res = await httpRequest('/api/getLoginType','POST',{
                phone:phone.value
            })
            if(res.data){
                if(res.data == 'code'){
                    clearInterval(timeId.value)
                    code.value = res.data
                    vcode.value.open()
                    uni.hideLoading()
                    uni.showToast({title:'验证码发送成功',icon:'none'})
                }else{
                    if(res.data.length<200)return
                    url.value = res.data
                    uni.hideLoading()
                    qrCode.value.open()
                    timeQRTime.value = 1
                }
            }
        }, 2000);

    }else{
        uni.showToast({title:'请输入正确的手机号',icon:'none'})
    }
}
const start = ref(0)
const timeId2 = ref()
const timer2 = ref()
//输入验证码发送给后端
const vcodeClick = async() => {
    uni.showLoading({
        title: '加载中',
        mask: true
    })
        httpRequest('/api/addReleTiktokCode','POST',{
        phone:phone.value,
        code:phoneCode.value,
        name:code.value
    })
    if(code.value == 'code'||code.value == 'codeError'){
        // 开启定时器请求是否会有特殊情况(扫二维码||二次验证)
        if(!timer2.value){
            timer2.value = setInterval(async() => {
            const res = await httpRequest('/api/getLoginType','POST',{
            phone:phone.value,
            name:'ewm2'
        })
        if(res.data){
            if(res.data.length<200)return
            url.value = res.data
            uni.hideLoading()
            qrCode.value.open()
        }
        }, 2000);
        }
    if(start.value != 2){
        timer.value = setInterval(async() => {
       if(start.value == 1){
        const res = await httpRequest('/api/getLoginType','POST',{
            phone:phone.value,
            name:'codeError1'
        })
        if(res.data == 'codeError1'){
            start.value = 2 //验证码输入错误情况第二次
            clearInterval(timer.value)
            uni.hideLoading()
            uni.showToast({title:'验证码输入错误',icon:'none'})
            code.value = res.data
            // vcode.value.open()
        }
       }else{
        const res = await httpRequest('/api/getLoginType','POST',{
            phone:phone.value,
            name:'codeError'
        })
        if(res.data == 'codeError'){
            start.value = 1 //验证码输入错误情况
            clearInterval(timer.value)
            uni.hideLoading()
            uni.showToast({title:'验证码输入错误',icon:'none'})
            code.value = res.data
            // vcode.value.open()
        }
       }
    }, 3000);
    }
    }else{
        //开启定时器请求是否会有特殊情况(扫二维码||二次验证)
    if(start.value != 2){
        timer.value = setInterval(async() => {
       if(start.value == 1){
        const res = await httpRequest('/api/getLoginType','POST',{
            phone:phone.value,
            name:'code2Error1'
        })
        if(res.data == 'code2Error1'){
            start.value = 2 //验证码输入错误情况第二次
            clearInterval(timer.value)
            uni.hideLoading()
            uni.showToast({title:'验证码输入错误',icon:'none'})
            code.value = res.data
            // vcode.value.open()
        }
       }else{
        const res = await httpRequest('/api/getLoginType','POST',{
            phone:phone.value,
            name:'code2Error'
        })
        if(res.data == 'code2Error'){
            start.value = 1 //验证码输入错误情况
            clearInterval(timer.value)
            uni.hideLoading()
            uni.showToast({title:'验证码输入错误',icon:'none'})
            code.value = res.data
            // vcode.value.open()
        }
       }
    }, 3000);
    }
    }
    

}

//分享给朋友
const share = () => {
    wx.showShareImageMenu({
          	needShowEntrance:true,
          	path: url.value,
          	success: function (res) {
          		console.log("success:" + JSON.stringify(res));
          	},
          	fail: function (err) {
              uni.hideLoading()
          		console.log("fail:" + JSON.stringify(err));
          	}
          });
}

//保存二维码图片
const save = () => {
    uni.showLoading({
        title: '正在保存',
        mask: true
    })
    uni.saveImageToPhotosAlbum({
			filePath: url.value,
			success: function () {
				console.log('save success');
			}
		});
    uni.hideLoading()
    uni.showToast({
        title: '保存成功',
        icon: 'success',
        mask: true
    })
}

//页面关闭清除定时器
onUnload(()=>{
    if(timeId.value)clearInterval(timeId.value)
    if(timer.value)clearInterval(timer.value)
    if(timeQR.value)clearInterval(timeQR.value)
})

const popupChange = (e) => {
    if(!e.show){
        // 停止运行
        httpRequest('/api/outLogin','POST')

        clearInterval(timeId.value)
        clearInterval(timer.value)
        clearInterval(timeId2.value)
        clearInterval(timer2.value)

    }
}
</script>

<template>
  <view class="page">
    <view class="tab">
        <view class="douyin" @click="isShow=0" :class="isShow==0?'active':''">抖音号</view>
        <view class="weixin" @click="isShow=1" :class="isShow==1?'active':''">视频号</view>
        <view class="line" :class="isShow==1?'line1':''"></view>
    </view>
    <view class="content">
        <!-- 没有手机号时显示的页面 -->
        <view class="kong" v-if="false">
            <image
              style="width: 610rpx; height: 368rpx"
              src="https://www.diandianyouke.site:801/fileDataBase/static/stag/static/img/state_empty.png"
            />
            <text>暂无账号</text>
        </view>   
            <view class="item" v-for="item in phoneList" :key="item.id">
                <text>{{ item.tiktokPhone }}</text>
                <image @click="delPhone(item.id)" style="width: 48rpx;height: 48rpx;" src="https://www.diandianyouke.site:801/fileDataBase/static/stag/static/img/zlsc_kbku_icon_schu.png"/>
            </view>
            <btnModule message="添加账号" @customClick="openInput" />
        </view>
  </view>
  <uni-popup ref="input">
    <view class="center">
        <view class="center-top">添加账号</view>
        <input class="phone" placeholder="输入手机号" v-model="phone" placeholder-class="place-class" type="text">
        <text class="tip">需要和绑定抖音的手机号一致</text>
        <view class="alert-btn">
            <view class="alert-quxiao" @click="closeInput">取消</view>
            <view class="alert-queren" @click="verify">确认</view>
        </view>
    </view>
  </uni-popup>
  <!-- 验证码弹窗 -->
  <uni-popup ref="vcode" @change="popupChange">
    <view class="vcode-content">
        <view class="vcode-title">账号验证</view>
        <input class="vcode-input" v-model="phoneCode" placeholder="输入验证码" type="text">
        <text>请输入发送至<text class="vcode-text">{{ phone }}</text>的验证码</text>
        <button @click="vcodeClick" class="vcode-button" hover-class="hover">确认</button>
    </view>
  </uni-popup>
  <!-- 二维码弹窗 -->
  <uni-popup ref="qrCode" @change="popupChange">
    <view class="qr-code">
        <image style="width: 522rpx;height: 442rpx;" src=""/>
        <image class="qrcode" :src="url"/>
        <view class="qr-view">
            <view class="qr-item">
                <image style="width: 32rpx;height: 32rpx;" src=""/>
                <text>刷新</text>
            </view>
            <view class="qr-item" @click="share">
                <image style="width: 32rpx;height: 32rpx;" src=""/>
                <text>转发</text>
            </view>
            <view class="qr-item" @click="save">
                <image style="width: 32rpx;height: 32rpx;" src=""/>
                <text>保存</text>
            </view>
        </view>
    </view>
  </uni-popup>
</template>

<style scoped lang="scss">
    .page{
        .tab{
            position: relative;
            width: 100%;
            height: 118rpx;
            display: flex;
            align-items: center;
            background-color: #fff;
            border-bottom: 1px solid rgb(220,223,230);
            .douyin{
                flex: 1;
                text-align: center;
                font-size: 32rpx;
                color: rgb(144,147,153);
            }
            .weixin{
                flex: 1;
                text-align: center;
                font-size: 32rpx;
                color: rgb(144,147,153);
            }
            .line{
                position: absolute;
                bottom: 0;
                left: 164rpx;
                width: 48rpx;
                height: 4rpx;
                background-color: rgb(142,84,244);
                border-radius: 118rpx;
                transition: all 0.3s ease;
            }
            .line1{
                left: 540rpx !important; 
            }
        }
        .content{
            padding: 30rpx;
            box-sizing: border-box;
            .kong {
                  width: 610rpx;
                  margin: 158rpx auto;
                  display: flex;
                  flex-direction: column;
                  align-items: center;
                  justify-content: center;
                  font-size: 24rpx;
                  color: rgb(144, 147, 153);
                }
                .item{
                    padding: 0 30rpx;
                    box-sizing: border-box;
                    display: flex;
                    justify-content: space-between;
                    align-items: center;
                    width: 690rpx;
                    height: 114rpx;
                    border-radius: 8rpx;
                    background-color: #fff;
                    font-size: 36rpx;
                    color: rgb(48,49,51);
                    margin-bottom: 30rpx;
                }
        }
    }
    .center{
        width: 582rpx;
        height: 404rpx;
        border-radius: 16rpx;
        background-color: #fff;
        box-sizing: border-box;
        overflow: hidden;
        .center-top{
            font-size: 34rpx;
            color: rgb(48,49,51);
            font-weight: 500;
            margin: 0 auto;
            text-align: center;
            margin-bottom: 30rpx;
            margin-top: 36rpx;
        }
        .phone{
            height: 88rpx;
            background-color: rgb(249,249,249);
            border-radius: 8rpx;
            margin: 0 30rpx 12rpx;
            padding-left: 24rpx;
        }
        .tip{
            display: block;
            font-size: 24rpx;
            color: rgb(252,139,0);
            margin-bottom: 36rpx;
            margin-left: 30rpx;
        }
        .alert-btn{
            display: flex;
            height: 116rpx;
            border-top: 1px solid rgb(235,238,245);
            position: absolute;
            bottom: 0;
            .alert-quxiao{
              width: 290rpx;
              height: 100%;
              border-right: 1px solid rgb(235,238,245);
              text-align: center;
              line-height: 116rpx;
              font-size: 34rpx;
              color: rgb(144, 147, 153);
            }

            .alert-queren{
              width: 290rpx;
              height: 100%;
              text-align: center;
              line-height: 116rpx;
              font-size: 34rpx;
              color: rgb(142, 84, 244);
            }
    
  }
    }
    .active{
        color: rgb(142,84,244) !important;
    }
    .place-class{
        font-size: 28rpx;
        color: rgb(144, 147, 153);
    }

    .vcode-content{
    width: 582rpx;
    height: 420rpx;
    border-radius: 16rpx;
    background-color: #fff;
    padding: 36rpx;
    box-sizing: border-box;
    font-size: 24rpx;
    color: rgb(144,147,153);

    .vcode-title{
        text-align: center;
        font-size: 34rpx;
        color: rgb(48,49,51);
    }
    .vcode-input{
        width: 510rpx;
        height: 88rpx;
        background-color: rgb(249,249,249);
        border-radius: 8rpx;
        padding: 0 24rpx;
        box-sizing: border-box;
        margin: 30rpx 0 18rpx 0;
    }
    .vcode-text{
        font-size: 24rpx;
        font-weight: 500;
        color: rgb(142, 84, 244);
        margin-bottom: 42rpx;
    }
    .vcode-button{
        width: 510rpx;
        height: 80rpx;
        border-radius: 8rpx;
        background-color: rgb(142, 84, 244);
        color: #fff;
        font-size: 32rpx;
        text-align: center;
        line-height: 80rpx;
        margin-top: 42rpx;
    }
    }
    .qr-code{
        width: 582rpx;
        padding: 36rpx 30rpx;
        box-sizing: border-box;
        background-color: #fff;
        .qrcode{
            display: block;
            width: 360rpx;
            height: 360rpx;
            margin: 36rpx auto 18rpx;
        }
        .qr-view{
            display: flex;
            width: 386rpx;
            align-items: center;
            justify-content: space-between;
            margin: 0 auto;
            .qr-item{
                width: 86rpx;
                display: flex;
                align-items: center;
                justify-content: space-between;
                font-size: 24rpx;
                color: rgb(144, 147, 153);
            }
        }

    }
</style>


